import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'base_service.dart';
import '../models/comment_model.dart';
import '../network/dio_client.dart';
import '../network/api_endpoints.dart';

class CommentService extends BaseService {
  final Dio _dio = DioClient().dio;
  /// 分页获取评论
  Future<List<Comment>> getCommentsPaginated(
      int page,
      int limit, {
        int? postId,
      }) async {
    try {
      final queryParameters = {
        '_page': page,
        '_limit': limit,
        '_sort': 'id',
        '_order': 'desc',
      };

      // 添加帖子ID筛选
      if (postId != null) {
        queryParameters['postId'] = postId;
      }

      final response = await _dio.get(
        ApiEndpoints.getComments,
        queryParameters: queryParameters,
        options: Options(extra: {'logResponse': true}),
      );

      logResponse(response);

      return extractData<List<Comment>>(response, (data) {
        return (data as List).map((commentJson) => Comment.fromJson(commentJson)).toList();
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('分页获取评论错误: $e');
      throw '获取评论失败';
    }
  }

  /// 分页获取用户的评论
  Future<List<Comment>> getCommentsByUserPaginated(
      int userId,
      int page,
      int limit,
      ) async {
    try {
      final response = await _dio.get(
        ApiEndpoints.getComments,
        queryParameters: {
          'userId': userId,
          '_page': page,
          '_limit': limit,
          '_sort': 'id',
          '_order': 'desc',
        },
        options: Options(extra: {'logResponse': true}),
      );

      logResponse(response);

      return extractData<List<Comment>>(response, (data) {
        return (data as List).map((commentJson) => Comment.fromJson(commentJson)).toList();
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('分页获取用户评论错误: $e');
      throw '获取用户评论失败';
    }
  }

// 获取所有评论
  Future<List<Comment>> getAllComments() async {
    try {
      final response = await _dio.get(ApiEndpoints.getComments,
          options: Options(extra: {'logResponse': true}));
      logResponse(response);

      return extractData<List<Comment>>(response, (data) {
        return (data as List)
            .map((commentJson) => Comment.fromJson(commentJson))
            .toList();
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('获取评论列表数据处理错误: $e');
      throw '获取评论列表失败';
    }
  }
  //添加按用户获取评论的方法
  Future<List<Comment>> getCommentsByUser(int userId) async {
    try {
      final response = await _dio.get(
        ApiEndpoints.getComments,
        queryParameters: {'userId': userId},
        options: Options(extra: {'logResponse': true}),
      );

      logResponse(response);

      return extractData<List<Comment>>(response, (data) {
        return (data as List).map((commentJson) => Comment.fromJson(commentJson)).toList();
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('获取用户评论列表错误: $e');
      throw '获取用户评论失败';
    }
  }
//获得单个评论详情
  Future<Comment> getComment(int id) async {
    try {
      final response = await _dio.get(ApiEndpoints.getComment(id),
          options: Options(extra: {'logResponse': true}));
      logResponse(response);
      return extractData<Comment>(response, (data) {
        return Comment.fromJson(data);
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('获得单个评论详情处理错误: $e');
      throw '获得单个评论详情失败';
    }
  }

  /// 创建新评论
  Future<Comment> createComment(Comment comment) async {
    try {
      final response = await _dio.post(
        ApiEndpoints.getComments,
        data: comment.toJson(),
        options: Options(
          extra: {'logRequest': true, 'logResponse': true},
        ),
      );
      logResponse(response);
      return extractData<Comment>(response, (data) {
        return Comment.fromJson(data);
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('创建新评论处理错误: $e');
      throw '创建新评论失败';
    }
  }
  /// 更新评论
  Future<Comment> updateComment(Comment comment) async {
    try {
      final response = await _dio.put(
        ApiEndpoints.getComment(comment.id),
        data: comment.toJson(),
        options: Options(
          extra: {'logRequest': true, 'logResponse': true},
        ),
      );

      logResponse(response);

      return extractData<Comment>(response, (data) {
        return Comment.fromJson(data);
      });
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('更新评论数据处理错误: $e');
      throw '更新评论失败';
    }
  }

  /// 删除评论
  Future<bool> deleteComment(int id) async {
    try {
      final response = await _dio.delete(
        ApiEndpoints.getComment(id),
        options: Options(extra: {'logRequest': true}),
      );

      logResponse(response);

      // 204 No Content 表示成功删除
      return response.statusCode == 200 || response.statusCode == 204;
    } on DioException catch (e) {
      throw handleDioError(e);
    } catch (e) {
      logger.e('删除评论处理错误: $e');
      throw '删除评论失败';
    }
  }

}
